(function ($) {
    $.fn.yqSvrAdNginx = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqSvrAdNginx.methods[opts](this, param);
        }

        var $this = this;
        var opt = $.extend({}, $.fn.yqSvrAdNginx.defaults, opts);

        if ($this.data("yqtype") == "yqSvrAdNginx") {
            var $uniqueID = $this.attr("ID");
            destroy($this);
            $this = $("#" + $uniqueID);
        }
        else {
            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        if (opt.width === undefined && $this.width() > 0) {
            opt.width = $this.width();
        }
        else if (typeof opt.width != "undefined") {
            $this.width(opt.width);
        }

        opt.serviceStatus = "inactive";

        //变量信息
        $this.data("svradnginx_opt", opt);
        $this.data("yqtype", "yqSvrAdNginx");

        init_ui($this);
    };

    $.fn.yqSvrAdNginx.defaults = {
        ajaxUrl: "/_svradmin.html",
        isEdit: true,
        afterBindingTitle: function () { },   //标题绑定后
    };

    $.fn.yqSvrAdNginx.methods = {
        options: function (jq) {
            return options(jq);
        },
        destroy: function (jq) {
            //destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize(jq, params);
        },

        isEdit: function (jq, tf) {
            //isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("svradnginx_opt");
    }

    function isEdit($object, tf) {
        var opt = options($object);
        if (tf === undefined) {
            tf = opt.isEdit;
        } else {
            opt.isEdit = tf;
        }

        updateButtonStates($object);
    }

    function destroy($object) {
    }

    function resize($object, params) {
        var opt = options($object);
        if (!(params === undefined)) {
            if (!(params.width === undefined)) {
                opt.width = params.width;
            }
            if (!(params.height === undefined)) {
                opt.height = params.height;
            }
        }

        var w_ = opt.width - 2;
        var h_ = opt.height - 48;
        if (h_ < 300) {
            h_ = 300;
        }

        opt.$div_json.yqCodeEdit("resize", {
            width: w_,
            height: h_,
        });
    }

    async function page_load($object) {
        var opt = options($object);

        const files = await getConfFiles($object);
        var data = [{
            id: "",
            text: "--select--"
        }];
        for (var i = 0; i < files.length; i++) {
            data.push({
                id: files[i],
                text: files[i],
            });
        }

        opt.$txt_conf.combobox("loadData", data);
        opt.$txt_conf.combobox("setValue", "");
        opt.$txt_conf.combobox("enable");

        resize($object);

        await checkStatus($object);

        opt.afterBindingTitle.call($object);
    }

    function init_ui($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("ID");
        var h_ = `
<table style="width: 100%;">
<tr>
    <td style="padding:4px 4px 4px 10px;white-space:nowrap;">
        <input class="btn_status"/>
        <a class="btn_restart"></a>
        <span style="padding-left: 15px;">配置文件</span>
        <select class="txt_conf"></select>
    </td>
    <td style="padding:4px 10px 4px 4px;text-align:right;">
        <a class="btn_log"></a>
        <span>当前状态：</span>
        <span class="txt_status"></span>
    </td>
</tr>
<tr>
    <td colspan="2">
        <div class="div_json" style="width:100%;height:400px;"></div>
    </td>
</tr>
</table>
        `;

        $object.html(h_);

        opt.$btn_status = $object.find(".btn_status");
        opt.$btn_restart = $object.find(".btn_restart");
        opt.$txt_conf = $object.find(".txt_conf");

        opt.$btn_log = $object.find(".btn_log");
        opt.$txt_status = $object.find(".txt_status");

        opt.$div_json = $object.find(".div_json");

        opt.$btn_status.switchbutton({
            width: 100,
            height: 35,
            handleWidth: 55,
            checked: false,
            handleText: "Nginx",
            onText: '开启',
            offText: '关闭',
            disabled: true,
        });

        opt.$btn_restart.linkbutton({
            width: 90,
            height: 35,
            text: "重启",
            iconCls: "yqwin-btn-icon fa fa-refresh",
            disabled: true,
            onClick: function () {
                restartService($object);
            }
        });

        opt.$txt_conf.combobox({
            valueField: 'id',
            textField: 'text',
            width: 320,
            height: 35,
            editable: false,
            panelHeight: 'auto',
            onSelect: function (record) {
                if (opt.$txt_conf_load === undefined) {
                    return;
                }

                //console.log("select", record);

                if (record.id == "") {
                    opt.$txt_conf_icon2.hide();
                    opt.$txt_conf_icon3.hide();
                    opt.$txt_conf_icon4.hide();
                    opt.$txt_conf_icon5.hide();
                    opt.$div_json.yqCodeEdit("setValue", "");
                    opt.$div_json.yqCodeEdit("disable");
                } else {
                    getConfFileJson($object, record.id, function (content) {
                        opt.$txt_conf_icon4.show();

                        if (record.id.split("/")[0] == "conf.d") {
                            opt.$txt_conf_icon2.show();
                            opt.$txt_conf_icon3.show();
                            opt.$txt_conf_icon5.show();
                        } else {
                            opt.$txt_conf_icon2.hide();
                            opt.$txt_conf_icon3.hide();
                            opt.$txt_conf_icon5.hide();
                        }

                        opt.$div_json.yqCodeEdit("setValue", content);
                        opt.$div_json.yqCodeEdit("enable");
                    });
                }

                opt.$txt_conf.combogrid('resize');
            },
            iconAlign: 'right',
            icons: [{
                iconCls: 'yqwin-combo-btn-icon fa fa-plus',
                handler: function (e) {
                    editFileName($object, this, "", "add");
                },
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-files-o',
                handler: function (e) {
                    var filename = opt.$txt_conf.combobox('getValue');
                    if (filename == "") {
                        $.yqMessager("error", "请先选择一个配置文件");
                        return;
                    }
                    var content = opt.$div_json.yqCodeEdit("getValue");
                    if (content == "") {
                        $.yqMessager("error", "文件没有配置内容");
                        return;
                    }
                    copyConfFile($object, filename, content);
                },
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-times',
                handler: function (e) {
                    var filename = opt.$txt_conf.combobox('getValue');
                    if (filename == "") {
                        $.yqMessager("error", "请先选择一个配置文件");
                        return;
                    }
                    if (filename.split("/")[0] != "conf.d") {
                        $.yqMessager("error", "请先选择一个配置文件");
                        return;
                    }
                    delConfFile($object, filename);
                },
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-floppy-o',
                handler: function (e) {
                    var filename = opt.$txt_conf.combobox('getValue');
                    if (filename == "") {
                        $.yqMessager("error", "请先选择一个配置文件");
                        return;
                    }
                    var content = opt.$div_json.yqCodeEdit("getValue");
                    saveConfFile($object, filename, content);
                },
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-underline',
                handler: function (e) {
                    console.log("rename");
                    var filename = opt.$txt_conf.combobox('getValue');
                    if (filename == "") {
                        $.yqMessager("error", "请先选择一个配置文件");
                        return;
                    }
                    editFileName($object, this, filename.split("/")[1].replace(/\.conf$/, ''), "upp");
                },
            }],
            onLoadSuccess: function (data) {
                if (!(opt.$txt_conf_load === undefined)) {
                    return;
                }
                opt.$txt_conf_load = true;

                var $icon0 = $(this).combogrid("getIcon", 0);
                var $icon5 = $(this).combogrid("getIcon", 5);
                $icon0.before($icon5);

                opt.$txt_conf_icon1 = $(this).combogrid("getIcon", 1);
                opt.$txt_conf_icon2 = $(this).combogrid("getIcon", 2);
                opt.$txt_conf_icon3 = $(this).combogrid("getIcon", 3);
                opt.$txt_conf_icon4 = $(this).combogrid("getIcon", 4);
                opt.$txt_conf_icon5 = $(this).combogrid("getIcon", 5);

                opt.$txt_conf_icon1.attr("title", "新建配置文件");
                opt.$txt_conf_icon2.attr("title", "拷贝配置文件");
                opt.$txt_conf_icon3.attr("title", "删除配置文件");
                opt.$txt_conf_icon4.attr("title", "保存配置文件");
                opt.$txt_conf_icon5.attr("title", "修改文件名称");

                opt.$txt_conf_icon2.hide();
                opt.$txt_conf_icon3.hide();
                opt.$txt_conf_icon4.hide();
                opt.$txt_conf_icon5.hide();

                opt.$txt_conf.combogrid('resize');
            },
        });

        opt.$btn_log.linkbutton({
            width: 90,
            height: 35,
            text: "参看日志",
            iconCls: "yqwin-btn-icon fa fa-refresh",
            disabled: true,
            onClick: function () {
                logService($object, this);
            }
        });

        opt.$div_json = opt.$div_json.yqCodeEdit({
            types: ["txt"],
            type: "txt",
            isEdit: false,
            value: "",
            goDocEnd: false,
        });

        page_load($object);
    }

    function editFileName($object, $this, filename, action) {
        var prevent_e = $.getPreventDefault($this);
        prevent_e.options = {
            beforeChange: function (data, callback) {
                if (data.value === "") {
                    $.yqMessager("error", "文件名不能为空");
                    callback(false, data);
                    return;
                }

                // 检查文件名是否合法
                var namePattern = /^[a-zA-Z0-9\-_.]+$/;
                if (!namePattern.test(data.value)) {
                    $.yqMessager("error", "文件名只能包含字母、数字、横线、下划线和点");
                    callback(false, data);
                    return;
                }

                callback(true, data);
            }
        };

        var mdiinfo = $.yqGetWindParams();
        var opt_ = {
            prevent_e: prevent_e,
            mdiinfo: mdiinfo,
            title: action == "add" ? "新建配置文件" : "修改文件名",
            width: 300,
            height: 144,
            horizontalAlign: "none",    //left,right,center,none
            verticalAlign: "none",      //top,bottom,center,none
            types: ["base"],
            type: "base",
            value: filename,
            isEdit: true,
            fontSize: 20,
            goDocEnd: false,  //加载后，显示在尾部

            callbackType: 1,   //返回value，2返回data
            callback: function (data) {
                console.log(action, 'conf.d/' + data.value + '.conf');
                if (action == "add") {
                    addConfFile($object, 'conf.d/' + data.value + '.conf');
                } else {
                    uppConfFile($object, 'conf.d/' + filename + '.conf', 'conf.d/' + data.value + '.conf');
                }
            }
        };

        if (window.top == window.self) {
            $.yqCodePopEdit(opt_);
        }
        else {
            window.top.$.yqCodePopEdit(opt_);
        }
    }

    // 检查服务状态
    async function checkStatus($object) {
        var opt = options($object);

        try {
            const response = await fetch(opt.ajaxUrl + `?action=nginx:status`);
            const data = await response.json();
            console.log("status", data);
            if (data.error == 0) {
                updateStatusDisplay($object, data.status);
            } else {
                $.yqMessager("error", data.info);
            }
        } catch (error) {
            $.yqMessager("error", '获取状态失败：' + error.message);
        }
    }

    // 执行服务操作
    async function executeServiceOperation($object, operation, actionName) {
        var opt = options($object);

        updateButtonStates($object);

        try {
            const response = await fetch(opt.ajaxUrl + "?action=nginx:" + operation, {
                method: 'POST'
            });
            const data = await response.json();
            console.log(operation, data);
            if (data.error == 0) {
                $.yqMessager("success", `${actionName}成功`);
            } else {
                $.yqMessager("error", data.info + `${actionName}失败`);
            }
        } catch (error) {
            $.yqMessage('error', error.info);
        } finally {
            await checkStatus($object);
        }
    }

    // 服务操作函数
    function startService($object) {
        executeServiceOperation($object, 'start', '启动服务');
    }

    function stopService($object) {
        executeServiceOperation($object, 'stop', '停止服务');
    }

    function restartService($object) {
        executeServiceOperation($object, 'restart', '重启服务');
    }

    function updateStatusDisplay($object, status) {
        var opt = options($object);

        opt.$txt_status.text(status === 'active' ? '运行中' : '已停止');
        opt.$txt_status.attr("class", 'status ' + status);
        opt.serviceStatus = status;
        updateButtonStates($object);
    }

    // 更新按钮状态
    function updateButtonStates($object) {
        var opt = options($object);

        var serviceStatus = opt.serviceStatus;

        if (serviceStatus === undefined || (!opt.isEdit)) {
            opt.$btn_status.switchbutton("disable");
            opt.$btn_restart.linkbutton("disable");
            opt.$txt_conf.combobox("disable");
            opt.$btn_log.linkbutton("disable");
            opt.$div_json.yqCodeEdit("disable");
            return;
        }

        opt.$btn_status.switchbutton(serviceStatus === 'active' ? "check" : "uncheck");
        opt.$btn_status.switchbutton("enable");
        opt.$btn_restart.linkbutton(serviceStatus === 'active' ? "enable" : "disable");
        opt.$txt_conf.combobox("enable");
        opt.$btn_log.linkbutton("enable");
        opt.$div_json.yqCodeEdit("enable");
        var status_opt = opt.$btn_status.switchbutton("options");
        status_opt.onChange = function (checked) {
            status_opt.onChange = function (checked) { };
            if (checked) {
                startService($object);
            } else {
                stopService($object);
            }
        };
    }

    function logService($object, $this) {
        var formData = new FormData();
        formData.append("action", "nginx:log");

        var opt = options($object);
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                console.log("log", res);
                if ($.yqDataErrCheck(res)) {
                    if (res.error == 0) {
                        var prevent_e = $.getPreventDefault($this);
                        prevent_e.options = {};

                        const width = Math.min(window.innerWidth, 1120);
                        const height = window.innerHeight - 40;

                        var show_pops = {
                            prevent_e: prevent_e,
                            mdiinfo: $.yqGetWindParams(),
                            title: "Nginx日志",
                            width: width,
                            height: height,
                            types: ["txt"],
                            type: "txt",
                            value: res.log,
                            isEdit: false,
                            goDocEnd: false,
                            callback: function (value) {
                                //b_value = value;
                            }
                        };

                        if (window.top == window.self) {
                            $.yqCodePopEdit(show_pops);
                        }
                        else {
                            window.top.$.yqCodePopEdit(show_pops);
                        }
                    } else {
                        $.yqMessager("error", "获取日志失败：" + res.info);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                $.yqMessager("error", "获取日志失败：" + errorThrown);
            }
        });
    }

    async function getConfFiles($object) {
        var opt = options($object);
        var files = [];
        try {
            const response = await fetch(opt.ajaxUrl + `?action=nginx:files`);
            const data = await response.json();
            console.log("status", data);
            if (data.error == 0) {
                files = data.files;
            } else {
                $.yqMessager('error', data.info);
            }
        } catch (error) {
            $.yqMessager('error', '获取状态失败：' + error.message);
        } finally {
            return files;
        }
    }

    function getConfFileJson($object, filename, callback) {
        if (filename == "") {
            callback("");
        }

        var formData = new FormData();
        formData.append("action", "nginx:file:get");
        formData.append("file", filename);

        var opt = options($object);
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    if (res.error == 0) {
                        callback(res.content);
                    } else {
                        $.yqMessager("error", res.info);
                        callback("");
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                $.yqMessager("error", "获取失败");
                callback("");
            }
        });
    }

    function saveConfFile($object, filename, content, callback) {
        if (filename == "") {
            return "";
        }

        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nginx:file:set");
        formData.append("file", filename);
        formData.append("content", content);

        isEdit($object, false);
        ajaxLoad(opt, formData, function (res) {
            if (res.error == 0) {
                if (!callback) {
                    $.yqMessager("success", "保存成功");
                }
            } else {
                $.yqMessager("error", res.info);
            }
            isEdit($object, true);

            if (callback) {
                callback(res.error == 0);
            }
        });
    }

    function addConfFile($object, filename, callback) {
        if (filename == "") {
            return "";
        }

        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nginx:file:add");
        formData.append("file", filename);

        isEdit($object, false);
        ajaxLoad(opt, formData, function (res) {
            if (res.error == 0) {
                if (!callback) {
                    $.yqMessager("success", "添加成功");
                }

                var data = opt.$txt_conf.combobox("getData");
                data.push({
                    id: filename,
                    text: filename,
                });

                opt.$txt_conf.combobox("loadData", data);
                opt.$txt_conf.combobox("setValue", filename);
            } else {
                $.yqMessager("error", "添加失败，" + res.info);
            }

            isEdit($object, true);

            if (callback) {
                callback(res.error == 0);
            };
        });
    }

    function copyConfFile($object, filename, content) {
        if (filename == "") {
            return "";
        }

        var opt = options($object);
        var s_filename = filename.split("/");
        var copy_filename = filename.replace(/\.conf$/, '') + "-copy.conf";

        addConfFile($object, copy_filename, function (tf) {
            if (tf) {
                saveConfFile($object, copy_filename, content, function (tf) {
                    if (tf) {
                        opt.$div_json.yqCodeEdit("setValue", content);
                        $.yqMessager("success", "拷贝成功");
                    }
                });
            }
        });
    }

    function uppConfFile($object, old_filename, new_filename) {
        if (old_filename == "" || new_filename == "") {
            return "";
        }

        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nginx:file:upp");
        formData.append("file", old_filename);
        formData.append("tofile", new_filename);

        isEdit($object, false);
        ajaxLoad(opt, formData, function (res) {
            if (res.error == 0) {
                $.yqMessager("success", "修改成功");
                var data = opt.$txt_conf.combobox("getData");
                for (var i = 0; i < data.length; i++) {
                    if (data[i].id == old_filename) {
                        data[i].id = new_filename;
                        data[i].text = new_filename;
                        break;
                    }
                }

                opt.$txt_conf.combobox("loadData", data);
                opt.$txt_conf.combobox("setValue", new_filename);
            } else {
                $.yqMessager("error", "修改失败，" + res.info);
            }

            isEdit($object, true);
        });

    }

    function delConfFile($object, filename) {
        if (filename == "") {
            return "";
        }

        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nginx:file:del");
        formData.append("file", filename);
        isEdit($object, false);
        ajaxLoad(opt, formData, function (res) {
            if (res.error == 0) {
                $.yqMessager("success", "删除成功");
                var data = opt.$txt_conf.combobox("getData");
                var data_new = [];
                for (var i = 0; i < data.length; i++) {
                    if (data[i].id != filename) {
                        data_new.push(data[i]);
                    }
                }

                opt.$txt_conf.combobox("loadData", data_new);
                opt.$txt_conf.combobox("setValue", "");

            } else {
                $.yqMessager("error", "删除失败，" + res.info);
            }

            isEdit($object, true);
        })
    }

    function ajaxLoad(opt, formData, callback) {
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    callback(res);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                callback({
                    error: 1,
                    info: "请求失败",
                });
            }
        });
    }
})(jQuery);
